﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Marbles.Core.Content.Pages;

namespace Marbles.Core.Controls
{
    [ToolboxData("<{0}:LoginControl runat=server></{0}:LoginControl>")]
    public class LoginControl : CompositeControl
    {

        public bool ReloadPageOnLogin
        {
            get { object obj = ViewState["ReloadPageOnLogin"]; return (obj == null) ? true : Convert.ToBoolean(obj); }
            set { ViewState["ReloadPageOnLogin"] = value; }
        }

        public bool AllowSiteChoice
        {
            get { object obj = ViewState["AllowSiteChoice"]; return (obj == null) ? false : Convert.ToBoolean(obj); }
            set { ViewState["AllowSiteChoice"] = value; }
        }

        private DropDownList drpSite;
        private Button btnLogin;
        private TextBox txtUsername;
        private TextBox txtPassword;
        private TableRow rowUsername;
        private TableRow rowPassword;
        private TableRow rowButtons;
        private TableCell cellButtons;
        private TableCell cellUsername1;
        private TableCell cellUsername2;
        private TableCell cellPassword1;
        private TableCell cellPassword2;
        private Button btnLogout;
        private Label lblStatus;
        private Label lblMessage;
        private TableRow rowSite;
        private TableCell cellSite1;
        private TableCell cellSite2;

        protected override void CreateChildControls()
        {
            Marbles.Core.Pages.Page p = this.Page as Marbles.Core.Pages.Page;

            if (p.AuthenticationProvider.IsAuthenticated)
            {
                btnLogout = new Button();
                lblStatus = new Label();
                this.Controls.Add(lblStatus);
                this.Controls.Add(btnLogout);
                lblStatus.Text = string.Format("Signed In as {0}<br/>", p.AuthenticationProvider.CurrentToken.Fullname);
                btnLogout.Text = "Logout";
                btnLogout.Click += new EventHandler(btnLogout_Click);
            }
            else
            {
                if (p.AuthenticationProvider.RequiresPassword)
                {
                    CreateChildControlsWithPassword();
                }
                else
                {
                    CreateChildControlsWithoutPassword();
                }
            }
        }

        private void CreateChildControlsWithPassword()
        {
            lblMessage = new Label();
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Visible = false;
            btnLogin = new Button();
            txtUsername = new TextBox();
            txtPassword = new TextBox();
            rowUsername = new TableRow();
            rowPassword = new TableRow();
            rowButtons = new TableRow();
            cellButtons = new TableCell();
            cellUsername1 = new TableCell();
            cellUsername2 = new TableCell();
            cellPassword1 = new TableCell();
            cellPassword2 = new TableCell();
            cellButtons.ColumnSpan = 2;
            txtPassword.TextMode = TextBoxMode.Password;
            Table tbl = new Table();
            tbl.CellPadding = 2;
            tbl.CellSpacing = 0;
            tbl.GridLines = GridLines.None;
            tbl.BorderStyle = System.Web.UI.WebControls.BorderStyle.None;
            this.Controls.Add(tbl);


            if (this.AllowSiteChoice)
            {
                drpSite = new DropDownList();
                rowSite = new TableRow();
                tbl.Rows.Add(rowSite);
                cellSite1 = new TableCell();
                cellSite2 = new TableCell();
                cellSite1.Text = "Site:";
                rowSite.Cells.Add(cellSite1);
                rowSite.Cells.Add(cellSite2);
                cellSite2.Controls.Add(drpSite);
                drpSite.DataValueField = "SiteId";
                drpSite.DataTextField = "Title";
                drpSite.AutoPostBack = true;
                drpSite.SelectedIndexChanged += new EventHandler(drpSite_SelectedIndexChanged);
                drpSite.DataSource = new Marbles.Core.Content.Sites.SiteDefinitionCollection();
                drpSite.DataBind();
                drpSite.ClearSelection();
                drpSite.Width = new Unit(200, UnitType.Pixel);
                string siteid = Marbles.Core.Content.Sites.SiteDefinition.GetCurrent().SiteId;
                foreach (ListItem item in drpSite.Items)
                {
                    if (item.Value == siteid) { item.Selected = true; break; }
                }
            }


            tbl.Rows.Add(rowUsername);
            tbl.Rows.Add(rowPassword);
            tbl.Rows.Add(rowButtons);

            rowUsername.Cells.Add(cellUsername1);
            rowUsername.Cells.Add(cellUsername2);
            rowPassword.Cells.Add(cellPassword1);
            rowPassword.Cells.Add(cellPassword2);
            rowButtons.Cells.Add(cellButtons);
            cellButtons.Controls.Add(btnLogin);
            cellButtons.Controls.Add(lblMessage);
            btnLogin.Text = "Login";
            btnLogin.Click += new EventHandler(btnLogin_Click);
            cellUsername1.Text = "Username:";
            cellPassword1.Text = "Password:";
            cellUsername2.Controls.Add(txtUsername);
            cellPassword2.Controls.Add(txtPassword);
        }

        protected void drpSite_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList drpSite = sender as DropDownList;
            Marbles.Core.Content.Sites.SiteDefinition web = Marbles.Core.Content.Sites.SiteDefinition.GetSiteBySiteId(drpSite.SelectedValue);
            if (web != null)
            {
                HttpContext.Current.Response.Redirect("http://" + web.Host + "/admin/", true);
            }
        }


        private void CreateChildControlsWithoutPassword()
        {
            lblMessage = new Label();
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Visible = false;
            btnLogin = new Button();
            txtUsername = new TextBox();
            rowUsername = new TableRow();
            rowButtons = new TableRow();
            cellButtons = new TableCell();
            cellUsername1 = new TableCell();
            cellUsername2 = new TableCell();
            cellButtons.ColumnSpan = 2;
            Table tbl = new Table();
            tbl.CellPadding = 2;
            tbl.CellSpacing = 0;
            tbl.GridLines = GridLines.None;
            tbl.BorderStyle = System.Web.UI.WebControls.BorderStyle.None;
            this.Controls.Add(tbl);
            tbl.Rows.Add(rowUsername);
            tbl.Rows.Add(rowButtons);
            rowUsername.Cells.Add(cellUsername1);
            rowUsername.Cells.Add(cellUsername2);
            rowButtons.Cells.Add(cellButtons);
            cellButtons.Controls.Add(btnLogin);
            cellButtons.Controls.Add(lblMessage);
            btnLogin.Text = "Login";
            btnLogin.Click += new EventHandler(btnLogin_Click);
            cellUsername1.Text = "Username:";
            cellUsername2.Controls.Add(txtUsername);
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            EnsureChildControls();
            Marbles.Core.Pages.Page p = this.Page as Marbles.Core.Pages.Page;
            lblMessage.Visible = false;

            if (p.AuthenticationProvider.Login(txtUsername.Text, txtPassword.Text))
            {
                
                if (ReloadPageOnLogin)
                {
                    HttpContext.Current.Response.Redirect(HttpContext.Current.Request.RawUrl, true);
                    return;
                }
            }
            else
            {
                lblMessage.Visible = true;
                lblMessage.Text = "Invalid Username or Password.";
            }
        }

        protected void btnLogout_Click(object sender, EventArgs e)
        {
            EnsureChildControls();
            Marbles.Core.Pages.Page p = this.Page as Marbles.Core.Pages.Page;
            p.AuthenticationProvider.Logout();
            HttpContext.Current.Response.Redirect(HttpContext.Current.Request.RawUrl, true);
        }
    }
}
